package com.lb.trac.web;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;


/**
 * Classe che carica in memoria le definizioni degli oggetti di ext per la creazione dell'interfaccia
 * @author edoardo
 *
 */
public class JSObjectManager extends DefaultHandler{

	private Map<String,Object> container = new HashMap<String, Object>();
	private List<String> xmlConfigsPath;
	
	public void init() throws Exception{
		for (Iterator<String> iterator = xmlConfigsPath.iterator(); iterator.hasNext();) {
			String completePath =  iterator.next();
			InputStream in = null;
			String path = null;
			if(completePath.indexOf("classpath:")!=-1){
				path = completePath.substring(completePath.indexOf("classpath:")+"classpath".length());
				in = new ClassPathResource(path).getInputStream();
			}
			if(completePath.indexOf("file:")!=-1){
				path = completePath.substring(completePath.indexOf("file:")+"file".length());
				in = new FileSystemResource(path).getInputStream();
			}
			parse(in);
		}
	}


	private void parse(InputStream in) throws ParserConfigurationException, SAXException, IOException {
		SAXParserFactory parserFactory = SAXParserFactory.newInstance();
		SAXParser parser = parserFactory.newSAXParser();
		in = XmlTableTransformerParser.class.getResourceAsStream("/com/setup/trac/web/etc/beans-mapper.xml");
		parser.parse(in, this);

	}
	
	


	public Map<String,Object> getContainer() {
		return container;
	}

	public void setXmlConfigsPath(List<String> xmlConfigsPath) {
		this.xmlConfigsPath = xmlConfigsPath;
	}

	public List<String> getXmlConfigsPath() {
		return xmlConfigsPath;
	}
	
}
